<?php
require_once('TVB/pms/pdes/action/CastGetAction.class.php');
require_once('TVB/pms/pdes/model/language.php');
require_once('TVB/pms/pdes/common/util/ChangeLogTools.class.php');

class CastUpdateAction extends BaseAction 
{
	/**
	 * @isnull false
	 */
	public $id;
	public $ades_id;
	public $programme_id;
	public $cast_role_id;
	public $gender;
	/**
     * @filter number
	 * @maxLength 85 
	 * @label Age
	 */
	public $age;
//	public $available_tag_types;
//	public $tags;
	public $blog_url;
	#public $folders;
	public $status;
	public $created_at;
	public $created_by;
	public $modified_at;
	public $modified_by;

	public $language_id;
	/**
	 * @maxLength 255
	 * @label Artistes Real First Name (Chinese)
	 */
	public $real_first_name_cn;
	
	/**
	 * @maxLength 255
	 * @label Artistes Real First Name (English)
	 */
	public $real_first_name_en;

	/**
	 * @maxLength 255
	 * @label Artistes Real Last Name (Chinese)
	 */
	public $real_last_name_cn;
	
	/**
	 * @maxLength 255
	 * @label Artistes Real Last Name (English)
	 */
	public $real_last_name_en;
	
	/**
	 * @maxLength 255
	 * @label Cast First Name (Chinese)
	 */
	public $first_name_cn;
	
	/**
	 * @maxLength 255
	 * @label Cast First Name (English)
	 */
	public $first_name_en;
	
	/**
	 * @maxLength 255
	 * @label Cast Last Name (Chinese)
	 */
	public $last_name_cn;
	
	/**
	 * @maxLength 255
	 * @label Cast Last Name (English)
	 */
	public $last_name_en;
	
	/**
	 * @maxLength 255
	 * @label Artistes Other Name (Chinese)
	 */
	public $other_name_cn;
	
	/**
	 * @maxLength 255
	 * @label Artistes Other Name (English)
	 */
	public $other_name_en;
	
	/**
	 * @maxLength 255
	 * @label Cast NickName (Chinese)
	 */
	public $nickname_cn;
	
	/**
	 * @maxLength 255
	 * @label Cast NickName (English)
	 */
	public $nickname_en;
	
	/**
	 * @maxLength 255
	 * @label Occupation (Chinese)
	 */
	public $occupation_cn;
	
	/**
	 * @maxLength 255
	 * @label Occupation (English)
	 */
	public $occupation_en;
	
	public $personality_cn;
	public $personality_en;
	
	public $profile_cn;
	public $profile_en;
	
	public $history_cn;
	public $history_en;

	public $tag;
	public $new_tag;

	public $from;
	public $episode_id;

	public $ut;
	public $reset;

    /*
     * for bug 786 
     * */
    public $is_folder_update;

	public function execute(){
		if (!is_null($this->reset))
		{
			$this->setData('id', $this->id);
			$this->setData('act', 'edit');
			$this->setData('step', 2);
			$this->setData('from', $this->from);
			return 'reset';
		}

		Model::$dbo['w']->beginTransaction();
		try{
			if (CommonUtils::is_concurrent('cast', $this->id, $this->modified_at))
			{
				$this->init_page_data();
				$this->addError('concurrent', array('0105', 'Concurrent update found!'));
				return 'logic-error';
			}

			if(count($this->_errors) > 0){
				$this->init_page_data();
				return 'filter-error';
			}

			$this->update_cast();
			$this->update_cast_language();
            $this->update_cast_multiple_language($this->id);
			
			# change_log
			$change_log  = array();
			$languages   = array(language::getLanguageId(AC::LANGUAGE_ZH),language::getLanguageId(AC::LANGUAGE_EN));
			$change_data = ChangeLogTools::getEpisodeIdsByCastId($this->id);
			$change_data['is_active']  = 1;
			$change_data['is_publish'] = 0;
			//for bug:7401    comment out the next line       #modified by Albie Lu on 2011-10-24
			//if(empty($change_data['programme_id']) && !empty($this->programme_id)) $change_data['programme_id'] = $this->programme_id;
			if(empty($change_data['episode_id']) && !empty($this->episode_id))     $change_data['episode_id'] = array($this->episode_id);
			$change_data['type'] = 'cast';
			$change_data['keys'] = array('id'=>$this->id);
			$change_log[] = $change_data; # cast 
			foreach($languages as $l){
				$change_data['type'] = 'cast-language';
				$change_data['keys'] = array('cast_id'=>$this->id,'language_id'=>$l);
				$change_log[] = $change_data; # cast language
			}

			/** just unpublished's cast need to write other change_log */
			$publish_log = publish_log::getPublishLog('cast',$this->id);
			if(
				(isset($publish_log->non_premium) && $publish_log->non_premium->status==AC::STATUS_UNPUBLISH) ||
				(isset($publish_log->premium)     && $publish_log->premium->status==AC::STATUS_UNPUBLISH_PREMIUM)
			){
				/** Add folder & folde_item to change_log for bug:7501 */
				foreach(explode(',',$this->_current_folders) as $fid){
					if(empty($fid)) continue;
					$change_data['type'] = 'folder';
					$change_data['keys'] = array('id'=>$fid);
					$change_log[] = $change_data;

					$change_data['type'] = 'image_folder-config';
					$change_data['keys'] = array('folder_id'=>$fid);
					$change_log[] = $change_data;

					foreach($languages as $l){
						$change_data['type'] = 'folder-language';
						$change_data['keys'] = array('folder_id'=>$fid,'language_id'=>$l);
						$change_log[] = $change_data;
					}

					/** Add image & image-language to change_log for bug:7330 */
					foreach(folder_item::getItemByFolderId($fid) as $image_id){
						$change_data['type'] = 'folder_item';
						$change_data['keys'] = array('folder_id'=>$fid,'item_id'=>$image_id);
						$change_log[] = $change_data;
						$change_data['type'] = 'image';
						$change_data['keys'] = array('id'=>$image_id);
						$change_log[] = $change_data;
						foreach($languages as $l){
							$change_data['type'] = 'image-language';
							$change_data['keys'] = array('image_id'=>$image_id,'language_id'=>$l);
							$change_log[] = $change_data;
							$change_data['type'] = 'folder_item-language';
							$change_data['keys'] = array('folder_id'=>$fid,'item_id'=>$image_id,'language_id'=>$l);
							$change_log[] = $change_data;
						}
					}
				}
			}

			array_walk($change_log,'change_log::updateOne');
            
            $primary_key = array(
                'cast_id' => $this->id
            );
            $fields = array(
                'real_first_name', 
                'real_last_name', 
                'first_name', 
                'last_name', 
                'other_name', 
                'nickname', 
                'occupation', 
                'personality', 
                'profile', 
                'history'
            );
            CommonUtils::filterC2A0('cast-language', $primary_key, $fields);

			Model::$dbo['w']->commit();

			$cast_role_type = cast_role::getCastRoleType($this->cast_role_id);

            if ($this->from == 'episode')
			{
                if ($this->is_folder_update) {
                    $this->setData('id', $this->id);
                    $this->setData('act', 'edit');
                    $this->setData('from', $this->from);
                    $this->setData('episode_id', $this->episode_id);
                    $this->setData('step', '2');

                    return 'folder';
                }

				$this->setData('id', $this->episode_id);
				$this->setData('act', 'edit');
				$this->setData('step', '2#anchor-'.strtolower($cast_role_type));

				return "episode";
			}
			elseif ($this->from == 'programme')
            {
                if ($this->is_folder_update) {
                    $this->setData('id', $this->id);
                    $this->setData('act', 'edit');
                    $this->setData('from', $this->from);
                    $this->setData('programme_id', $this->programme_id);
                    $this->setData('step', '2');

                    return 'folder';
                }

				$this->setData('id', $this->programme_id);
				$this->setData('act', 'edit');
				$this->setData('step', '2#anchor-'.strtolower($cast_role_type));
				return "programme";
			}
			elseif ($this->from == 'task')
			{
				return 'task';
			}
			else
			{	
                if ($this->is_folder_update) {
                    $this->setData('act', 'edit');
                    $this->setData('step', '2');
                    $this->setData('id', $this->id);

                    return 'folder';
                }

				$this->setData('type','cast');
				return 'succ';
			}
		}
		catch(Exception $e)
		{
			error_log("Update Cast Fails: $this->id");
			error_log("Exception: " . var_export($e,1));
			error_log("Request: " . var_export($this, 1));

			Model::$dbo['w']->rollBack();

			return 'system-error';
		}
	}    

	/**
	 * update cast
	 */
	private function update_cast()
	{
		$cast = new cast();
		$cast = $cast->get($this->id);
		Model::diff($cast, $this);
		$cast->modified_at = date("Y-m-d H:i:s", $_SERVER['REQUEST_TIME']);
		$cast->modified_by = CommonUtils::get_user();
        $cast->age = isset($this->age) ? trim($this->age) : '';
		$this->_current_folders = $cast->folders;
		$update_id = Model::$dbo['w']->save($cast);
		if ($update_id > 0)
		{
			$this->addInfo("cast:".AC::LOG_OP_UPDATE.":".$this->id, "update cast success", json_encode($cast));
		}
		else
		{
			$this->addError("cast:".AC::LOG_OP_UPDATE.":".$this->id, "update cast failed", json_encode($cast));
		}
	}

	/**
	 * update cast language
	 */
	private function update_cast_language()
	{	
		$language_id_cn = language::getLanguageId(AC::LANGUAGE_ZH);
		
		$cast_language = new cast_language();
		Model::$dbo['w']->delete('cast_language', 
								 'cast_id=? AND language_id=?', 
								 array('cast_id' => $this->id, 'language_id' => $language_id_cn));
		$cast_language->set($this);
		
		$cast_language->cast_id = $this->id;
		$cast_language->language_id = $language_id_cn;
		$cast_language->real_first_name = isset($this->real_first_name_cn) ? trim($this->real_first_name_cn) : '';
		$cast_language->real_last_name  = isset($this->real_last_name_cn) ? trim($this->real_last_name_cn) : '';
		$cast_language->first_name = isset($this->first_name_cn) ? trim($this->first_name_cn) : '';
		$cast_language->last_name  = isset($this->last_name_cn) ? trim($this->last_name_cn) : '';
		$cast_language->other_name = isset($this->other_name_cn) ? trim($this->other_name_cn) : '';
		$cast_language->nickname   = isset($this->nickname_cn) ? trim($this->nickname_cn) : '';
		$cast_language->occupation = isset($this->occupation_cn) ? trim($this->occupation_cn) : '' ;
		$cast_language->personality = isset($this->personality_cn) ? $this->personality_cn : '';
		$cast_language->profile = isset($this->profile_cn)? $this->profile_cn : '';
		$cast_language->history = isset($this->history_cn)? $this->history_cn : '';
		
		$update_id = Model::$dbo['w']->save_by_fields($cast_language, array('cast_id','language_id'));
		if ($update_id > 0)  {
			$this->addInfo("cast-language:".AC::LOG_OP_UPDATE.":".$this->id, 
						   "update cast language success", 
						   json_encode($cast_language));
		} else {
			$this->addError("cast-language:".AC::LOG_OP_UPDATE.":".$this->id, 
							"update cast language failed", 
							json_encode($cast_language));
		}
	}
	
	private function update_cast_multiple_language()
	{
		$language_id_en = language::getLanguageId(AC::LANGUAGE_EN);

		$cast_language = new cast_language();
		Model::$dbo['w']->delete('cast_language', 
								 'cast_id=? AND language_id=?', 
								 array('cast_id' => $this->id, 'language_id' => $language_id_en));
		$cast_language->set($this);
		
		$cast_language->cast_id = $this->id;
		$cast_language->language_id = $language_id_en;
		$cast_language->real_first_name = isset($this->real_first_name_en) ? trim($this->real_first_name_en) : '';
		$cast_language->real_last_name  = isset($this->real_last_name_en) ? trim($this->real_last_name_en) : '' ;
		$cast_language->first_name = isset($this->first_name_en) ? trim($this->first_name_en) : '';
		$cast_language->last_name  = isset($this->last_name_en) ? trim($this->last_name_en) : '';
		$cast_language->other_name = isset($this->other_name_en) ? trim($this->other_name_en) : '';
		$cast_language->nickname   = isset($this->nickname_en) ? trim($this->nickname_en) : '';
		$cast_language->occupation = isset($this->occupation_en) ? trim($this->occupation_en) : '';
        $cast_language->personality =isset($this->personality_en) ? $this->personality_en : '';
		$cast_language->profile = isset($this->profile_en) ? $this->profile_en : '';
		$cast_language->history = isset($this->history_en) ? $this->history_en : '';
		
		$update_id = Model::$dbo['w']->save_by_fields($cast_language, array('cast_id','language_id'));
		if ($update_id > 0) {
			$this->addInfo("cast-language:".AC::LOG_OP_UPDATE.":".$this->id, 
						   "update cast language success", 
						   json_encode($cast_language));
		} else {
			$this->addError("cast-language:".AC::LOG_OP_UPDATE.":".$this->id, 
							"update cast language failed", 
							json_encode($cast_language));
		}
	}

	/**
	 * init page data
	 */
	private function init_page_data()
	{
		$action = new CastGetAction();
		$action->id = $this->id;
		$action->act = 'edit';
		$action->step = 2;
		$action->execute();

		$old_data = $action->getData();
		$this->modified_at = $old_data['cast']->modified_at;
		$old_data['cast'] = Model::diff($old_data['cast'], $this);
		$old_data['cast']->cast_language[1] = array(
			'real_first_name'	=> $this->real_first_name_cn, 
			'real_last_name'	=> $this->real_last_name_cn, 
			'first_name'		=> $this->first_name_cn, 
			'last_name'			=> $this->last_name_cn, 
			'other_name'		=> $this->other_name_cn, 
			'nickname'			=> $this->nickname_cn, 
			'occupation'		=> $this->occupation_cn, 
			'personality'		=> $this->personality_cn, 
			'profile'			=> $this->profile_cn, 
			'history'			=> $this->history_cn
		);
		$old_data['cast']->cast_language[2] = array(
			'real_first_name'	=> $this->real_first_name_en, 
			'real_last_name'	=> $this->real_last_name_en, 
			'first_name'		=> $this->first_name_en, 
			'last_name'			=> $this->last_name_en, 
			'other_name'		=> $this->other_name_en, 
			'nickname'			=> $this->nickname_en, 
			'occupation'		=> $this->occupation_en, 
			'personality'		=> $this->personality_en, 
			'profile'			=> $this->profile_en, 
			'history'			=> $this->history_en
		);
		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
		}

		//jump page
		$this->setData('id', $this->id);
		$this->setData('type', 'cast');
		$this->setData('act', 'edit');
		$this->setData('from', $this->from);
		$this->setData('step', 2);
	}
}
?>
